<template>
  <a-card :bordered="false">
    <h3>发券管理</h3>
    <IndexFilter
      ref="indexFilter"
      :visibleTemplat.sync="visibleTemplat"
      :visibleTemplatOne.sync="visibleTemplatOne"
      @handleExportOfficeSends="handleExportOfficeSends"
      @handleExportOfficeSendsDetails="handleExportOfficeSendsDetails"
      @handleSubmitChangeTemplat="handleSubmitChangeTemplat"
      @handleIssue="handleIssue"
      @onSearch="onSearch"></IndexFilter>
    <s-table
      ref="table"
      size="default"
      :rowKey="record => record.id"
      :columns="columns"
      :data="loadData"
      :pagination="paginationProps"
      :scroll="{ x: 1300 }"
    >
      <span slot="sendType" slot-scope="record">
        <span v-if="record.sendType == 1">微信券</span>
        <span v-if="record.sendType == 2">礼券</span>
        <span v-if="record.sendType == 3">纸质券</span>
      </span>
      <span slot="action" slot-scope="record">
        <a @click="handleRecord(record.id)">明细</a>
        <a-divider type="vertical" />
         <a @click="handleOpenDelay(record)">延期</a>
          <!-- <a v-else style="color: #666;">延期</a> -->
        <a-divider type="vertical" v-if="record.sendType == 2 || record.sendType == 3" />
        <a @click="handlePrint(record.id)" v-if="record.sendType == 2 || record.sendType == 3">补打印</a>
        <a-divider type="vertical" v-if="record.sendType == 2" />
        <a @click="handleOpenTemplatModal(record.id)" v-if="record.sendType == 2">领券模版</a>
        <a-divider type="vertical"/>
        <a @click="handleOpenCancel(record)">作废</a>
        <a-divider type="vertical"/>
        <a @click="handleOpenLog(record.id)">日志</a>
      </span>
    </s-table>
    <a-modal v-model="visibleIssue" width="700px" title="发券" @cancel="visible = false" @ok="handleIssueConfirm">
      <a-form-model ref="issueForm" :model="issueForm" :rules="issueRules">
        <template v-if="oaList.length">
          <a-form-model-item label="发券原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="season">
            <a-radio-group v-model="issueForm.season">
              <a-radio :value="1">相关部门申请（{{oaList.length}}）</a-radio>
              <a-radio :value="2">自主创建</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <template v-if="issueForm.season == 1">
            <a-form-model-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="department">
              <a-select v-model="issueForm.department" show-search :filter-option="filterOption">
                <a-select-option :value="item.id" v-for="(item, index) in oaList" :key="index">
                  {{ item.department }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="申请用途" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div style="line-height: 20px;vertical-align: middle;display: inline-block;">{{usefor}}</div>
            </a-form-model-item>
          </template>
          <template v-if="issueForm.season == 2">
            <a-form-model-item label="申请用途" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-model="issueForm.remarks" show-search allowClear :filter-option="filterOption">
                <a-select-option value="关系维护">关系维护</a-select-option>
                <a-select-option value="活动">活动</a-select-option>
                <a-select-option value="对外费用支付">对外费用支付</a-select-option>
                <a-select-option value="员工福利">员工福利</a-select-option>
                <a-select-option value="调整新增">调整新增</a-select-option>
              </a-select>
            </a-form-model-item>
          </template>
        </template>
        <a-form-model-item label="发券类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
          <a-radio-group v-model="issueForm.sendType">
            <a-radio :value="1">微信券</a-radio>
            <a-radio :value="2">礼券</a-radio>
            <a-radio :value="3">纸质券</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <LogModal :visible.sync="visibleLog" :pagination.sync="logPagination" :data="logData" @onPageChange="onPageChange"></LogModal>
    <CommonModal :type="1" :visible.sync="visibleDelay" @onCommonModalOk="handleVoucherDelay"></CommonModal>
    <CommonModal :type="2" :visible.sync="visibleCancel" @onCommonModalOk="handleVoucherCancel"></CommonModal>
  </a-card>
</template>
<script>
  import { couponList, sendPageAdd, voucherCancel, voucherDelay, printDetails, oaList, pageUpdate, exportOfficeSends, officeLog, exportOfficeSendsDetails } from '@/api/headquartersCoupon/index'
  import { STable } from '@/views/box/components'
  import { LogModal, CommonModal, IndexFilter } from './components/index'
  import qs from 'qs'
  import { mapGetters } from 'vuex'
  const columns = [
    {
      title: '发券类型',
      width: 100,
      align: 'center',
      scopedSlots: { customRender: 'sendType' }
    },
    {
      title: '批次号',
      width: 100,
      align: 'center',
      dataIndex: 'id'
    },
    {
      title: '最小券号',
      width: 150,
      align: 'center',
      dataIndex: 'smallNo'
    },
    {
      title: '最大券号',
      width: 150,
      align: 'center',
      dataIndex: 'bigNo'
    },
    {
      title: '申请时间',
      width: 200,
      align: 'center',
      dataIndex: 'modifiedtime'
    },
    {
      title: '领用部门',
      width: 150,
      align: 'center',
      dataIndex: 'department'
    },
    {
      title: '备注',
      width: 200,
      align: 'center',
      dataIndex: 'remarks'
    },
    {
      title: '领用券金额',
      width: 100,
      align: 'center',
      dataIndex: 'totalAmount'
    },
    {
      title: '券面值',
      width: 100,
      align: 'center',
      dataIndex: 'amt'
    },
    {
      title: '领用券总数量',
      width: 100,
      align: 'center',
      dataIndex: 'totalNum'
    },
    {
      title: '适用店铺',
      width: 100,
      align: 'center',
      dataIndex: 'stores'
    },
    {
      title: '使用数量',
      width: 100,
      align: 'center',
      dataIndex: 'useNum'
    },
    {
      title: '未使用数量',
      width: 100,
      align: 'center',
      dataIndex: 'noUseNum'
    },
    {
      title: '过期数量',
      width: 100,
      align: 'center',
      dataIndex: 'validNum'
    },
    {
      title: '作废数量',
      width: 100,
      align: 'center',
      dataIndex: 'cancelNum'
    },
    {
      title: '操作',
      width: 200,
      align: 'center',
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    components: {
      IndexFilter,
      STable,
      LogModal,
      CommonModal
    },
    data() {
      return {
        pageId: '',
        logPagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
        },
        logData: [{
          id: 1
        }],
        visibleLog: false,
        visibleCancel: false,
        exportOfficeSends,
        exportOfficeSendsDetails,
        recordLength: 0,
        current: 1,
        size: 10,
        couponId: '',
        oaList: [],
        record: {},
        issueConfirmFlag: false,
        visible: false,
        visibleTemplat: false,
        visibleTemplatOne: false,
        visibleDelay: false,
        issueForm: {
          sendType: 1,
          department: '',
          season: 1
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visibleIssue: false,
        issueRules: {
          season: [{ required: true, message: '请选择', trigger: 'change' }],
          department: [{ required: true, message: '请选择', trigger: 'change' }],
          sendType: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        columns,
        paginationProps: {
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
          // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
        },
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const data = {
            ...this.queryParam,
            current: parameter.pageNo,
            size: parameter.pageSize
          }
          this.current = parameter.pageNo
          this.size = parameter.pageSize
          return couponList(data).then(res => {
            if (res.code === 200) {
              const { records, total, current, size, pages } = res.data
              this.recordLength = records.length
              const data = {
                page: {
                  count: total,
                  pageNo: current,
                  pageSize: size,
                  pages
                },
                data: records
              }
              return data
            } else {
              this.$message.error(res.msg || res.message)
              this.recordLength = 0
              const data = {
                page: {
                  count: 0,
                  pageNo: 0,
                  pages: 0
                },
                data: []
              }
              return data
            }
          })
        }
      }
    },
    created() {
      this.getOaList()
      console.log(this.userInfo(), 'userinfo')
    },
    computed: {
      usefor() {
         const list = this.oaList.filter(e => e.id == this.issueForm.department)
          if (list.length) {
            return list[0].usefor
          } else {
            return ''
          }
      }
    },
    mounted() {
    },
    watch: {
      $route(to, from) {
        if ((from.path.includes('/headquarters-coupon/print') || from.path.includes('headquarters-coupon/record')) && to.path.includes('/headquarters-coupon/index')) {
          this.$refs.table.refresh()
        } else {
          let currentPath = this.$route.path
          if (currentPath.includes('/headquarters-coupon/index') ) {
            this.$refs.indexFilter.reset()
          }
        }
      }
    },
    methods: {
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      // 打开日志弹出
      handleOpenLog(id) {
        this.visibleLog = true
        this.pageId = id
        this.logPagination.current = 1
        this.getOfficeLog()
      },

      // 获取日志
      getOfficeLog() {
        const data = {
          logType: [2, 3, 4],
          pageId: this.pageId,
          current: this.logPagination.current,
          size: this.logPagination.pageSize
        }
        officeLog(data).then(res => {
          if (res.code === 200) {
            const { records, total } = res.data
            this.logData = records
            const pagination = { ...this.logPagination }
            pagination.total = total
            this.logPagination = pagination
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 日志分页
      onPageChange(v) {
        console.log(v, 'vvvv')
        this.logPagination = v
        this.getOfficeLog()
      },

      // 下载汇总表
      handleExportOfficeSends() {
        if (!this.recordLength) {
          this.$message.warning('暂无数据可下载')
          return
        }
        const that = this
        const data = {
          ...that.queryParam,
            current: that.current,
            size: that.size
        }
        window.location.href = `${that.exportOfficeSends}?${qs.stringify(data)}`
        // this.$confirm({
        //   content: () => `确认要下载当前${this.recordLength}条数据吗？`,
        //   onOk() {
        //     const data = {
        //       ...that.queryParam,
        //         current: that.current,
        //         size: that.size
        //     }
        //     window.location.href = `${that.exportOfficeSends}?${qs.stringify(data)}`
        //   },
        //   onCancel() {}
        // })
      },

      // 下载核销明细
      handleExportOfficeSendsDetails() {
        if (!this.recordLength) {
          this.$message.warning('暂无数据可下载')
          return
        }
        const that = this
        const data = {
          ...that.queryParam,
            current: that.current,
            size: that.size
        }
        window.location.href = `${that.exportOfficeSendsDetails}?${qs.stringify(data)}`
      },

      // 更改领券模板弹窗
      handleOpenTemplatModal(id) {
        this.couponId = id
        this.visibleTemplatOne = true
      },

      // 更改领券模板
      handleSubmitChangeTemplat(v) {
        const data = {
          applyTemplateId: v,
          id: this.couponId
        }
        pageUpdate(data).then(res => {
          if (res.code === 200) {
            this.visibleTemplatOne = false
            this.$notification['success']({
              message: '系统提示',
              description: res.msg,
              duration: 4
            })
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },
      
      // 补打印
      handlePrint(id) {
        const data = {
          pageId: id
        }
        printDetails(data).then(res => {
          if (res.code === 200) {
            const data = decodeURIComponent(JSON.stringify(res.data))
            this.$router.push(`/headquarters-coupon/print/1?data=${data}`)
          } else {
            this.$message.warning(res.msg || res.message)
          }
        }).catch(err => {
        })
      },

      // 流程列表
      getOaList() {
        const data = {
          current: 1,
          size: 100
        }
        oaList(data).then(res => {
          if (res.code === 200) {
            this.oaList = res.data.records
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },
  
      // 发券
      handleIssue() {
        this.visibleIssue = true
      },

      // 确定发券
      handleIssueConfirm() {
        this.$refs.issueForm.validate(valid => {
          if (valid) {
            if (this.issueConfirmFlag) return
            this.issueConfirmFlag = true
            const data = {
              ...this.issueForm
            }
            sendPageAdd(data).then(res => {
              if (res.code == 200) {
                const id = this.issueForm.season == 1 ? this.issueForm.department : ''
                const {remarks, sendType} = this.issueForm
                const currentRemarks = this.issueForm.season == 2 ? remarks : ''
                this.issueConfirmFlag = false
                this.visibleIssue = false
                this.$router.push(`/headquarters-coupon/addAndEdit/${res.data}?sendType=${sendType}&id=${id}&remarks=${currentRemarks || ''}`)
                this.issueForm.remarks = ''
              } else {
                this.issueConfirmFlag = false
                this.$message.warning(res.msg || res.message)
              }
            })
          } else {
            return false
          }
        })
      },
      
      // 作废
      handleOpenCancel(record) {
        this.record = record
        this.visibleCancel = true
      },

      // 作废
      handleVoucherCancel(v) {
        const {id, bigNo, smallNo} = this.record
        const data = {
          pageId: id,
          // nos: [
          //   {
          //     vouchersNoEnd: bigNo,
          //     vouchersNoStart: smallNo
          //   }
          // ],
          ...v
        }
        voucherCancel(data).then(res => {
          if (res.code === 200) {
            this.visibleCancel = false
            this.$refs.table.refresh()
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 延期弹窗
      handleOpenDelay(record) {
        this.record = record
        this.visibleDelay = true
      },

      // 延期
      handleVoucherDelay(v) {
        const {id, bigNo, smallNo} = this.record
        if (!id) return
        const data = {
          pageId: id,
          // nos: [
          //   {
          //     vouchersNoEnd: bigNo,
          //     vouchersNoStart: smallNo
          //   }
          // ],
          ...v
        }
        voucherDelay(data).then(res => {
          if (res.code === 200) {
            this.visibleDelay = false
             this.$notification['success']({
              message: '系统提示',
              description: res.msg,
              duration: 4
            })
            this.$refs.table.refresh()
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 明细
      handleRecord(id) {
        this.$router.push(`/headquarters-coupon/record/${id}`)
      },

      //查询
      onSearch(obj) {
        this.queryParam = obj
        this.$refs.table.refresh(true)
      },

      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      }
    }
  }
</script>
<style lang="less" scoped>
  .show-img {
    display: block;
    width: 100%;
  }

  .details-wrapper {
    display: flex;
    padding-bottom: 40px;

    .main-img {
      display: block;
      width: 40%;
    }

    .text {
      flex: 1;
      margin-left: 10%;
      line-height: 35px;
      font-size: 14px;
    }
  }

  .id-wrapper {
    font-size: 12px;
    text-align: center;

    span {
      color: #999;
    }
  }

  .product-img {
    font-size: 12px;

    .img-item {
      display: inline-block;
      vertical-align: middle;
      margin: 0 5px;
      text-align: center;
    }
  }

  .time {
    font-size: 12px;
    color: #999;
  }

  .img {
    display: block;
    margin: 2px auto;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
    cursor: pointer;
  }
</style>
